<template>
    <div>
        <Modal v-model="xiao" :footer-hide="true" class="sw" width="260" height="260" @mask-click="handleClose">
            <div class="qrcode" ref="qrCodeUrl" id="qrcode"></div>
            <p class="cen">{{ this.storeID }}</p>
        </Modal>
        <Card title="门店基本信息展示">
            <Row>
                <Button v-if="this.data2.length > 0" icon="md-create" @click="popupBtn">修改门店信息</Button>
                <Button v-else icon="md-create">加载中...</Button>
                <Button @click="creatQrCode">查看门店二维码</Button>
            </Row>
            <Table class="table-all-width" :show-header="false" border :loading="loading" :columns="columns1"
                :data="data1">
            </Table>
        </Card>

        <Modal :mask-closable="false" v-model="popup" @on-cancel="closeModals" title="修改门店信息">
            <Form ref="formItem" :rules="ruleValidate" :model="formItem" :label-width="80">
                <FormItem label="门店名称" prop="storeName">
                    <Input v-model="formItem.storeName" placeholder="请输入门店名称" clearable></Input>
                </FormItem>
                <FormItem label="营业时间" prop="businessTime">
                    <TimePicker type="timerange" confirm @on-ok="timeChang" format="HH:mm"
                        v-model="formItem.businessTime" :editable="false" placement="bottom-start"
                        placeholder="请选择营业时间"></TimePicker>
                </FormItem>
                <FormItem label="门店地址" prop="storeAdd">
                    <!-- <Cascader :render-format="format" v-model="formItem.storeAdd" @on-change="storeaddset"
            :data="$store.state.user.datalist2.length>0 && [...$store.state.user.datalist2[0]]" trigger="hover">
          </Cascader> -->
                    <!-- <Cascader :render-format="format" v-model="formItem.storeAdd" @on-change="storeaddset"
            :data="data2" trigger="hover">
          </Cascader> -->
                    <KeepAlive>
                        <Cascader :render-format="format" v-model="formItem.storeAdd" @on-change="storeaddset"
                            :data="data2" trigger="hover">
                        </Cascader>
                    </KeepAlive>
                </FormItem>
                <FormItem label>
                    <Input v-model="formItem.addres" class="inputAddres" placeholder="请填写详细信息"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="close('formItem')" size="large">取消</Button>
                <Button type="primary" size="large" @click="doSomething('formItem')">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { getBussinessType } from "./keyList";
import { menuInfo, saveMenuInfo, menuInfoKey } from "@/api/loginMenu";
import QRCode from "qrcodejs2";
import { getTableData } from "../../api/city";
export default {
    name: "storeListtwoVue",
    data() {
        return {
            aa: false,
            city: {},
            popup: false,
            xiao: false,
            bian: false,
            storeCodeId: "",
            loading: false,
            storeID: "",
            columns1: [
                {
                    title: "Name",
                    key: "name",
                    width: 100,
                    align: "center",
                    className: "tab-font-color"
                },
                {
                    title: "title",
                    key: "title"
                }
            ],
            data1: [],
            formItem: {
                storeName: "",
                businessTime: [],
                storeAdd: [],
                addres: ""
            },
            newTime: "",
            upDataTime: "",
            data2: [],
            data3: [{
                value: 'beijing',
                label: '北京',
                children: [
                    {
                        value: 'gugong',
                        label: '故宫'
                    },
                    {
                        value: 'tiantan',
                        label: '天坛'
                    },
                    {
                        value: 'wangfujing',
                        label: '王府井'
                    }
                ]
            }, {
                value: 'jiangsu',
                label: '江苏',
                children: [
                    {
                        value: 'nanjing',
                        label: '南京',
                        children: [
                            {
                                value: 'fuzimiao',
                                label: '夫子庙',
                            }
                        ]
                    },
                    {
                        value: 'suzhou',
                        label: '苏州',
                        children: [
                            {
                                value: 'zhuozhengyuan',
                                label: '拙政园',
                            },
                            {
                                value: 'shizilin',
                                label: '狮子林',
                            }
                        ]
                    }
                ],
            }],
            addressMap: [],
            ruleValidate: {
                storeName: [
                    {
                        required: true,
                        message: "门店名称不能为空",
                        trigger: "blur"
                    }
                ],
                storeAdd: [
                    {
                        required: true,
                        message: "所在区域不能为空",
                        trigger: "change",
                        type: "array"
                    }
                ],
                businessTime: [
                    {
                        required: true,
                        validator: this.dataTime,
                        trigger: "change"
                    }
                ]
            }
        };
    },
    computed: {
        // ...mapState({
        //   datalist2: state => {
        //     console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
        //     return state.user.datalist2[0]
        //   } 
        // }),
    },
    methods: {

        loadData(item, callback) {
            console.log(item, 'item');
            callback();
        },


        handleClose() {
            // 处理关闭模态框的逻辑
            console.log(1233);
        },
        creatQrCode() {
            console.log(this.storeID);
            if (this.bian == true) {
                var qrcode = new QRCode(this.$refs.qrCodeUrl, {
                    // 这里选择器也可以直接写 'qrcode' 用的是id选择器   指示不需要带 # 而已
                    text: `https://retail.tongfupay.com/v1/basic/storeInfo/bindYunDianStoreId.no?fromSys=yunDian&storeCode=${this.storeID}`, //  生成二维码的 内容
                    // text: `https://retailtest.tongfupay.com/v1/basic/storeInfo/bindYunDianStoreId.no?fromSys=yunDian&storeCode=${this.storeID}`, //  生成二维码的 内容
                    width: 150, //  宽   单位 px
                    height: 150, //  高   单位 px
                    // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                    // background: '#f0f'
                    // foreground: '#ff0'
                    correctLevel: QRCode.CorrectLevel.H // 二维码容错 级别
                });
            }

            this.xiao = true;
            this.bian = false
            console.log(this.$refs.qrCodeUrl);
        },

        menuInfo(storeCode) {
            menuInfo(storeCode).then((res) => {
                const storeData = res.data;
                if (storeData.code == 200) {
                    this.storeCodeId = storeData.data.id;
                    this.handleData1(storeData.data);
                    let arr = []
                    if (storeData.data.provinceId && storeData.data.cityId && storeData.data.areaId) {
                        arr.push(storeData.data.provinceId)
                        arr.push(storeData.data.cityId)
                        arr.push(storeData.data.areaId)
                    }
                    // this.$set(this.formItem, 'storeAdd', arr);
                    localStorage.setItem("arr", JSON.stringify(arr))
                }
            });
        },
        dataTime(rule, value, callback) {
            if (value[0] == "" || value[1] == "") {
                callback(new Error("请选择营业时间"));
            } else {
                callback();
            }
        },
        timeChang() {
            let newdata =
                this.formItem.businessTime[0] + " — " + this.formItem.businessTime[1];
            this.newTime = newdata;
        },
        handleData1(storeInfo) {
            let longitudeInfo = null;
            if (storeInfo.longitude == null || storeInfo.latitude == null) {
                longitudeInfo = "";
            } else {
                longitudeInfo = storeInfo.longitude + " —— " + storeInfo.latitude;
            }

            const keyList = [
                {
                    name: "门店名称",
                    key: "storeName",
                    title: storeInfo.storeName
                },
                {
                    name: "门店编号",
                    key: "storeCode",
                    title: storeInfo.storeCode
                },
                {
                    name: "门店类型",
                    key: "storeType",
                    title: storeInfo.storeType
                },
                {
                    name: "门店品牌",
                    key: "storeBrand",
                    title: storeInfo.storeBrand
                },
                {
                    name: "所在区域",
                    key: "province-area",
                    title:
                        storeInfo.province + "-" + storeInfo.city + "-" + storeInfo.area
                },
                {
                    name: "详细地址",
                    key: "address",
                    title: storeInfo.address
                },
                {
                    name: "经纬度",
                    key: "longitude@latitude",
                    title: longitudeInfo
                },
                {
                    name: "业态",
                    key: "bussinessType",
                    title: getBussinessType(storeInfo.bussinessType)
                },
                {
                    name: "联系人",
                    key: "linkName",
                    title: storeInfo.linkName
                },
                {
                    name: "手机号",
                    key: "linkMobile",
                    title: storeInfo.linkMobile
                },
                {
                    name: "邮箱",
                    key: "linkEmail",
                    title: storeInfo.linkEmail
                },
                {
                    name: "营业时间",
                    key: "storeBrand",
                    title: storeInfo.businessTime
                }
            ];
            this.data1 = keyList;
            // this.menuInfoKey()
        },
        closeModals() {
            this.close("formItem");
        },
        close(name) {
            this.$refs[name].resetFields();
            this.popup = false;
        },
        // 修改门店
        async popupBtn() {
            // if (!this.data2.length > 0) {
            //   await getChilds().then((res) => {
            //     console.log(res, 'resreswww');
            //     // this.addressMap = res.RESULT;
            //     if (res) {
            //       this.data2 = [...res]
            //     }
            //   })
            // }
            let arr = JSON.parse(localStorage.getItem("arr")) || []
            console.log(arr, this.data2);
            if (this.data2.length > 0) {
                console.log('aaaqqq');
                this.formItem.storeAdd = [...arr];
                this.aa = true
            }
            this.formItem.businessTime = [];
            this.formItem.storeName = this.data1[0].title;
            // this.getCode();
            console.log(this.formItem.storeAdd);
            this.newTime = "";
            let newbussTime = this.data1[11].title;
            if (newbussTime) {
                this.formItem.businessTime.push(
                    newbussTime.substring(0, 5),
                    newbussTime.substring(7, 13)
                );
            } else {
                this.formItem.businessTime.push("", "");
            }

            this.formItem.addres = this.data1[5].title;
            this.popup = true;
        },
        // 经纬度
        async menuInfoKey() {
            const addLists = this.data1[4].title;
            const item = {
                address: addLists.replace(/-/g, "")
            };
            const { data, status } = await menuInfoKey(item);
            console.log(data, 'aaa');
            if (status == 200) {
                let longitude = data.data;
                this.data1[6].title = longitude.replace(/,/g, "——");
            }
        },
        // 保存信息
        doSomething(name) {
            console.log(name, 'aaaaaaa');
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.storeListLoading = this.$myLoading({
                        content: "正在保存,请稍等..."
                    });
                    this.data1[0].title = this.formItem.storeName;
                    this.data1[5].title = this.formItem.addres;
                    this.data1[11].title =
                        this.formItem.businessTime[0] +
                        " — " +
                        this.formItem.businessTime[1];
                    const addList = this.formItem.storeAdd;
                    let add = this.city;
                    // console.log(addList, 'addList');
                    // addList.forEach((item) => {

                    //   add.push(this.getLabel(item));
                    // });
                    console.log(add, 'add');
                    const obj = {
                        storeName: this.formItem.storeName,
                        province: add[0],
                        city: add[1],
                        area: add[2],
                        address: this.formItem.addres,
                        id: this.storeCodeId,
                        businessTime:
                            this.formItem.businessTime[0] +
                            " — " +
                            this.formItem.businessTime[1]
                    };
                    console.log(obj, 'obj');
                    saveMenuInfo(obj).then((res) => {
                        this.data1[4].title = add.join("-");
                        this.popup = false;
                        setTimeout(() => {
                            this.closeModals();
                            this.storeListLoading.close();
                            this.$Message.success("保存成功!");
                            this.menuInfoKey();
                        }, 0);
                    });
                } else {
                    this.$Message.error("保存失败！");
                }
            });
        },
        // 省市value对应label
        // getCode() {
        //   console.log('aaaaaaaaaaaaaaaaaaddddddddddddddddddddd');
        //   const labelList = this.data1[4].title.split("-");
        //   let arr = [];
        //   labelList.forEach((item) => {
        //     arr.push(this.getValue(item));
        //   });
        //   if (arr.length > 1) {
        //     if (arr[0] == arr[1]) {
        //       arr[1] = "" + (+arr[1] + 100);
        //     }
        //   }
        //   console.log(arr, 'arr');
        //   // arr = [' 130000', '130100','130184']
        //   this.formItem.storeAdd = arr;
        // },
        // getValue(label) {
        //   console.log(this.addressMap,'aaaaaaaaaaaaaaaaaadddddddddddddddddddddcccccccccccccccc');
        //   for (let i = 0; i < this.addressMap.length; i++) {
        //     const item = this.addressMap[i];
        //     if (item.label == label) {
        //       return item.value;
        //     }
        //   }
        // },
        storeaddset(value, selectedData) {
            console.log(6666);
            console.log(value, selectedData);
            let Obj = [];
            let arr = [];
            Obj.push(selectedData[0].label)
            Obj.push(selectedData[1].label)
            Obj.push(selectedData[2].label)
            arr.push(selectedData[0].value)
            arr.push(selectedData[1].value)
            arr.push(selectedData[2].value)
            // {
            //   "province": selectedData[0].label,
            //   "city": selectedData[1].label,
            //   "area": selectedData[2].label,
            // }
            localStorage.setItem("arr", JSON.stringify(arr))
            this.city = [...Obj]
        },
        getLabel(value) {
            console.log(this.addressMap, 'aaaaaaaaaaaaaaaaaadddddddddddddddddddddccccccccddddddd');
            for (let i = 0; i < this.addressMap.length; i++) {
                const item = this.addressMap[i];
                if (item.value == value) {
                    return item.label;
                }
            }
        },
        format(labels, selectedData) {
            return labels.join("-");
        }
    },
    async created() {
        if (!this.data2.length > 0) {
            await getTableData().then((res) => {
                console.log(res, 'resres');
                this.data2 = [...res.data.data]
            })
        }
    },
    mounted() {
        // if (!this.data2.length>0) {
        //   this.data2 = [...this.$store.state.user.datalist2]
        // }
        // this.creatQrCode(); // 这里会是一个重点，下面会解释
        // let storeInfoJSON = ;

        this.bian = true
        let storeInfo = JSON.parse(localStorage.getItem("storeInfo"));
        // chinaCity().then((res) => {
        //   this.data2 =res
        // })
        // getChilds().then((res) => {
        //   console.log(res, 'resreswww');
        //   this.addressMap = res.RESULT;
        //   this.data2 = res.list
        // this.addressMap =[

        //         {
        //           "value": "130123",
        //           "label": "正定县",
        //           "children": null
        //         },
        //         {
        //           "value": "130184",
        //           "label": "新乐市",
        //           "children": null
        //   },
        //   {
        //     "value": "130000",
        //     "label": "河北省",
        //   } ,{
        //     "value": "130100",
        //     "label": "石家庄市",
        //   }
        //       ]
        // this.data2 = [{
        //   "value": "130000",
        //   "label": "河北省",
        //   "children": [
        //     {
        //       "value": "130100",   
        //       "label": "石家庄市",
        //       "children": [

        //         {
        //           "value": "130123",
        //           "label": "正定县",
        //           "children": null
        //         },
        //         {
        //           "value": "130184",
        //           "label": "新乐市",
        //           "children": null
        //         }
        //       ]
        //     },
        //   ]
        // }]
        // })
        // console.log(this.addressMap,'this.addressMap');
        this.storeID = storeInfo.storeCode;
        this.menuInfo(storeInfo.storeCode);

    }
};
</script>

<style>
.qrcode {
    display: flex;
    justify-content: center;
    align-items: center;
}

.ivu-table-wrapper {
    margin-top: 15px;
}

.ivu-table td.tab-font-color {
    font-weight: bold;
    color: #333;
}

.ivu-modal-confirm-head-title {
    margin-top: -5px;
    margin-bottom: 15px;
}

.cen {
    text-align: center;
    margin-top: 10px;
    font-size: 20px;
}
</style>
